import routeNames from "../../utils/routeNames";
import {useLocation, useNavigate} from "react-router-dom";
import Token from "../../models/Token";
import {useContext, useEffect, useState} from "react";
import {getTokenById} from "../../http/tokenApi";
import {UserContext} from "../../index";
import {getUserById} from "../../http/userApi";
import UserInfo from "../../models/UserInfo";
import {getImageById} from "../../http/imageApi";
import handleImageNotLoaded from "../../functions/handleImageNotLoaded";
import BuyTokenDto from "../../utils/dto/wallet/buyTokenDto";
import {buyToken} from "../../http/purchaseApi";

const ProjectDetailsPage = () => {
    const navigate = useNavigate();
    const location = useLocation();
    const {tokenId} = location.state || {};
    const userStore = useContext(UserContext);

    const getDefaultTokenData = (): Token => {
        return {
            id: "defaultId",
            name: "Default Token Name",
            imageId: "defaultImageId",
            tokenPrice: 10,
            tokenSymbol: "DTN",
            createdDate: new Date(),
            chainId: "chainId",
            targetedRaise: 100000,
            totalRaise: 75999.7,
            tokenSummary: "Nice token",
            createdBy: userStore.user.userInfoId,
            participants: 999
        };
    };

    const [token, setToken] = useState<Token>(getDefaultTokenData());
    const [createdByUser, setCreatedByUser] = useState<UserInfo | null>();

    useEffect(() => {
        if (tokenId) {
            getTokenById(tokenId)
                .then(async response => {
                    if (response.status === 200) {
                        setToken(response.data);
                        setCreatedByUser(await getUserById(response.data.createdBy))
                    } else {
                        alert(response.statusText);
                    }
                })
        }
    }, []);

    const handleClaimClick = () => {
        let dto = new BuyTokenDto(token.id)
        buyToken(dto)
            .then(response => {
                if (response.status === 200)
                    alert("Токен успешно куплен")
                else
                    alert(response.statusText)
            })
    }

    console.log(token)

    return (
        <>
            <div className="gamfi-breadcrumbs-section breadcrumbs-style2">
                <div className="container">
                    <div className="row">
                        <div className="col-lg-5">
                            <div className="breadcrumbs-area sec-heading">
                                <div className="sub-inner">
                                    <a className="breadcrumbs-link" onClick={() => navigate(routeNames.HOME_PAGE)}
                                       style={{cursor: 'pointer'}}>Home</a>
                                    <a className="breadcrumbs-link"
                                       onClick={() => navigate(routeNames.PROJECTS_LIST_PAGE)}
                                       style={{cursor: 'pointer'}}>Project List</a>
                                    <span className="sub-title">Project Details</span>
                                    <img className="heading-left-image" src="/assets/images/icons/steps.png"
                                         alt="Steps-Image"/>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div className="project-details-conent gamfi-about-secion pb-80 md-pb-20">
                <div className="container">
                    <div className="game-price-item hover-shape-inner">
                        <div className="game-price-inner">
                            <div className="total-price">
                                <div className="price-inner d-flex mb-45">
                                    <div className="image-icon">
                                        <img src={getImageById(token.imageId)} style={{width: "120px", height: "120px"}}
                                             alt="icon-image" onError={handleImageNotLoaded}/>
                                    </div>
                                    <div className="price-details">
                                        <h3 className="mb-15">{token.name}</h3>
                                        <div className="dsc">price ({token.tokenSymbol}) = {token.tokenPrice} BUSD</div>
                                    </div>
                                </div>
                                <div className="all-raise mb-10"> Total Raise {token.totalRaise} BUSD
                                    ( {((token.totalRaise / token.targetedRaise) * 100).toFixed(2)}% )
                                </div>
                            </div>
                            <div className="allocation-max text-center">
                                <img src="/assets/images/project/icon-2.png" alt="icon-image"/>
                            </div>
                            <div className="targeted-raise">
                                <div className="all-raise mb-10">Sale End In</div>
                                <div className="price-counter mb-48">
                                    <div className="timer timer_1">
                                        <ul>
                                            <li className="days"></li>
                                            <li className="hours"></li>
                                            <li className="minutes"></li>
                                            <li className="seconds"></li>
                                        </ul>
                                    </div>
                                </div>
                                <div className="targeted-raise text-end">
                                    Targeted Raise {token.targetedRaise} BUSD
                                </div>
                            </div>
                        </div>
                        <div className="progress-inner">
                            <div className="progress">
                                <div className="progress-bar progress-bar-striped" role="progressbar"
                                     aria-valuenow={parseInt(((token.totalRaise / token.targetedRaise) * 100).toFixed(2), 10)}
                                     aria-valuemin={0} aria-valuemax={100}
                                     style={{width: `${((token.totalRaise / token.targetedRaise) * 100).toFixed(2)}%`}}>
                                </div>
                            </div>
                        </div>
                        <div className="banner-bottom-content mt-40">
                            <div className="btn-area" onClick={handleClaimClick}>
                                <a className="readon white-shape-small" style={{cursor: 'pointer'}}>
                                    <span className="btn-text">Claim Token </span>
                                    <span className="hover-shape1"></span>
                                    <span className="hover-shape2"></span>
                                    <span className="hover-shape3"></span>
                                </a>
                            </div>
                            <div className="text-content">
                                Participants {token.participants}/5000
                            </div>
                        </div>
                        <span className="border-shadow shadow-1"></span>
                        <span className="border-shadow shadow-2"></span>
                        <span className="border-shadow shadow-3"></span>
                        <span className="border-shadow shadow-4"></span>
                        <span className="hover-shape-bg hover_shape1"></span>
                        <span className="hover-shape-bg hover_shape2"></span>
                        <span className="hover-shape-bg hover_shape3"></span>
                    </div>
                    <div className="row mt-30">
                        <div className="col-md-6">
                            <div className="project-item">
                                <div className="project-info">
                                    <h4 className="mb-30">{token.name} <img
                                        src="/assets/images/project/project-heading-image.png" alt="project"/></h4>
                                </div>
                                <div className="project-content">
                                    <div className="project-media">
                                        <ul className="project-listing">
                                            <li>Token Distribution <span>Date UTC</span></li>
                                            <li>Token Price <span>1 BUSD = 555.55 SIDUS</span></li>
                                            <li>Access type <span>Public</span></li>
                                        </ul>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div className="col-md-6">
                            <div className="project-item">
                                <div className="project-info d-flex">
                                    <h4 className="mb-20">Token Info <img
                                        src="/assets/images/project/project-heading-image.png" alt="project"/></h4>
                                </div>
                                <div className="project-content">
                                    <div className="project-media">
                                        <ul className="project-listing">
                                            <li>Token Name <span>{token.name}</span></li>
                                            <li>Token Symbol <span>{token.tokenSymbol}</span></li>
                                            <li>Total
                                                Supply <span>{token.totalRaise * token.tokenPrice} {token.tokenSymbol}</span>
                                            </li>
                                        </ul>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div className="row mt-50 main-content" data-spy="scroll" data-target="#myScrollspy"
                         data-offset="20">
                        <div className="col-md-4 sidebar">
                            <div className="project-summary-menu project_summary_menu_BgGridient sidebar__inner"
                                 id="myScrollspy">
                                <div id="ProjectSammeryTabs" className="project_summary_tabs_sect">
                                    <div className="active project-summary-tab-btn  project-summary-tab-btn1"
                                         data-target="#project_summary"><a href="#project_summary">Project Summary <img
                                        src="/assets/images/project/menu-image.png" alt="project"/></a></div>
                                    <div className="project-summary-tab-btn project-summary-tab-btn6"
                                         data-target="#Team_Members"><a href="#team_Members">Team Member <img
                                        src="/assets/images/project/menu-image.png" alt="project"/></a></div>
                                </div>
                            </div>
                        </div>
                        <div className="col-md-8 pl-35 sm-pl-15 sm-pt-40">
                            <div className="project_summarySectScrllab">
                                <div className="project-summary-content" id="project_summary">
                                    <div className="project-summary-information">
                                        <h4 className="title2 mb-15">Project Summary</h4>
                                        <p>{token.tokenSummary}</p>
                                    </div>
                                </div>

                                <div className="ScrollSpy_sections" id="Team_Members">
                                    <h4 className="title2 mb-15">Team Members</h4>
                                    <div className="project_details_team_members_sect">
                                        <div className="row">
                                            <div className="col-lg-3 col-sm-6">
                                                <div className="project_details_team_members_card"
                                                     style={{padding: '20px'}}>
                                                    <div className="team_members_img">
                                                        <img src={getImageById(createdByUser?.imageId)}
                                                             alt="User Avatar" onError={handleImageNotLoaded}
                                                             className="img-fluid"/>
                                                    </div>
                                                    <h5>{createdByUser?.firstName} {createdByUser?.lastName}</h5>
                                                    <h6>{createdByUser?.userName}</h6>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </>
    )
}

export default ProjectDetailsPage